﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Audio;
using System.IO.IsolatedStorage;
using System.IO;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Input.Touch;
using GameStateManagement;
using Microsoft.Phone.Shell;
using System.Xml.Serialization;
using System.Net.Sockets;
using System.Net;

namespace PiratesOfBermuda
{
    public class HostGameProcessor : MultiPlayerGameProcessor
    {
        bool isClientConnected = false;

        //Game Logic Management
        //public bool isPlayerTurn;
        public bool isClientTurn;

        public HostGameProcessor(Game game, SpriteBatch spriteBatch) 
            : base(game, spriteBatch)
        {
            //Khoi gan luot choi
            //Host di dau tien
            isPlayerTurn = true;
            //Opponent choi luot sau
            isClientTurn = false;            
        }

        #region PROCESS PACKETS
        protected override void checkConnectedState(UdpPacketReceivedEventArgs e)
        {
            if (!isClientConnected && e.Message.Contains("ClientConnecting"))
            {
                string[] mess = e.Message.Split(',');
                opponentIndentifier = mess[0];
                Channel.Send("HostAccepted");
                GeneratePlayer(ref player, 0, 5, "Host");
                GeneratePlayer(ref opponentPlayer, 10, 5, "Client");
                player.LifeRemained = playerLifeRemained;
                opponentPlayer.LifeRemained = opponentLifeRemained;
                Channel.Send("Init,Host,{0},{1}", player.X, player.Y);
                Channel.Send("Init,Client,{0},{1}", opponentPlayer.X, opponentPlayer.Y);
                GenerateGameObjects();
                Channel.Send("InitDone");
                isClientConnected = true;
            }
        }

        protected override void handleMessagesFromOpponent(string[] mess)
        {
            switch (mess[1])
            {
                case "Move":
                case "MoveAndWhirl":
                    ObjectsCustomMove(mess);
                    break;
                // Nguoi choi con lai chuyen luot sang cho enemy
                case "ChangeTurn":
                    isClientTurn = false;
                    ProcessEnemiesMove();
                    break;

                //Nhan thong diep tan cong tu Client
                case "Fire":
                    handleFireEventFromOpponent(mess);
                    break;
            }
        }

        protected void ProcessEnemiesMove()
        {
            //List<string> positions = new List<string>();
            foreach (BasicEnemy enemy in enemies)
            {
                enemy.IsActive = true;
                Point nextMove = enemy.GetNextMove(player.X, player.Y, opponentPlayer.X, opponentPlayer.Y);
                Channel.Send("Move,Enemy,{0},{1},{2},{3}", enemy.X, enemy.Y, nextMove.X, nextMove.Y);
                enemy.Move(nextMove.X, nextMove.Y);
            }
            if (enemies.Count != 0)
                AudioManager.PlaySound("MoveEvil");
            //return positions;
        }
        #endregion

        #region UPDATE
        public override void GenerateGameObjects()
        {
            GenerateWhirls();
            sendMessages();
            GenerateIslands();
            sendMessages();
            GenerateEnemies();
            sendMessages();
        }

        public override void CheckGameObjectsState()
        {
            //Neu tau cua minh da het luot
            if (player.CurrentShipState == ShipState.Standby && isPlayerTurn && !player.IsActive)
            {
                isPlayerTurn = false;
                //Chuyen luot sang cho Client
                isClientTurn = true;
                Channel.Send("ChangeTurn");
            }
            //Truong hop neu tau cua Host da het mang thi chuyen luot ngay, khong xu ly
            else if (player.CurrentShipState == ShipState.Ended && isPlayerTurn && gameState == GameState.Playing)
            {
                isPlayerTurn = false;
                //Chuyen luot sang cho doi phuong
                isClientTurn = true;
                Channel.Send("ChangeTurn");
            }
            if (gameState == GameState.Playing)
            {
                if (player.CurrentShipState == ShipState.Ended
                    && opponentPlayer.CurrentShipState == ShipState.Ended
                    && enemies.Count != 0)
                {
                    Channel.Send("GameStateChanged,PlayerLose");
                    gameState = GameState.PlayerLose;
                }
                if (enemies.Count == 0)
                {
                    if (player.CurrentShipState == ShipState.Ended
                    && opponentPlayer.CurrentShipState != ShipState.Ended)
                    {
                        Channel.Send("GameStateChanged,ClientWin");
                        gameState = GameState.PlayerLose;
                    }
                    else if (player.CurrentShipState != ShipState.Ended
                    && opponentPlayer.CurrentShipState == ShipState.Ended)
                    {
                        Channel.Send("GameStateChanged,HostWin");
                        gameState = GameState.PlayerWin;
                    }
                    else if (player.CurrentShipState == ShipState.Ended
                    && opponentPlayer.CurrentShipState == ShipState.Ended)
                    {
                        Channel.Send("GameStateChanged,AllDead");
                        gameState = GameState.AllDead;
                    }
                }
            }
        }

        public override void Update(GameTime gameTime)
        {
            if (isClientConnected)
            {
                CheckGameObjectsState();
                base.Update(gameTime);
                UpdatePlayer(gameTime);
                UpdateOpponentPlayer(gameTime);
            }
        }

        protected override void UpdateEnemies(GameTime gameTime)
        {
            //Neu la luot cua AI
            if (!isPlayerTurn && !isClientTurn)
            {
                if (handleEnemiesUpdateEvent())
                {
                    isPlayerTurn = true;
                    player.IsActive = true;
                    opponentPlayer.IsActive = true;
                }
                sendMessages();
            }
            //update tung enemy nhu binh thuong
            foreach (BasicEnemy enemy in enemies)
            {
                enemy.Update(gameTime);
            }

            //sendMessages();
        }        

        protected override void removeSpecifiedShip(string key)
        {
            if (gameObjects[key].GetType() == typeof(BasicEnemy))
            {
                base.removeSpecifiedShip(key);
            }
            else if (gameObjects[key].GetType() == typeof(Player))
            {
                gameObjects[key].Destroyed = true;
            }
        }
        
        protected override bool handlePlayersDestroyedEvent(ref Player tempPlayer)
        {
            bool alive = base.handlePlayersDestroyedEvent(ref tempPlayer);
            if (alive)
                Channel.Send(messages[0]);
            else
                Channel.Send(messages[0]);
            return alive;
        }

        protected override void UpdatePlayer(GameTime gameTime)
        {
            UpdateCustomPlayer(ref player, gameTime);
            sendMessages();
        }

        public override void UpdateOpponentPlayer(GameTime gameTime)
        {
            UpdateCustomPlayer(ref opponentPlayer, gameTime);
            sendMessages();
        }
        #endregion

        #region DRAW

        protected override void CheckAndDrawGameObjects(GameTime gameTime)
        {
            if (isClientConnected && player != null && opponentPlayer != null)
            {
                base.CheckAndDrawGameObjects(gameTime);
            }
        }

        protected override void CheckAndDrawAnimations()
        {
            if (!isPlayerTurn && !isClientTurn && isDone)
            {
                DrawExplodeAnimations();
            }
        }

        #endregion

        #region Player Helper Method
        public override void HandleInput(List<GestureSample> gestures)
        {
            if (isClientConnected && isPlayerTurn && player.IsActive && gameState == GameState.Playing)
            {
                HandleUserInput(gestures, "Host");
                sendMessages();
            }
        }
        #endregion
    }
}